<?php

namespace app\api\controller;

use app\BaseController;
use app\api\model\Star as StarModel;
use app\api\model\Article as ArticleModel;
use app\api\model\Voice as VoiceModel;
use app\api\model\Video as VideoModel;

class Star extends BaseController
{
    public function initialize()
    {
        $this->uid = $this->request->uid;
    }

    /* 点赞、取消点赞 */
    public function index()
    {
        if (!$this->request->auth) return show(config('status.auth'), '认证失败');

        $type = input('type', 0, 'intval');
        $rid = input('rid', 0, 'intval');

        $one = StarModel::where(['uid' => $this->uid, 'type' => $type, 'rid' => $rid])->find();
        if (!$one) {
            StarModel::create([
                'uid' => $this->uid,
                'type' => $type,
                'rid' => $rid,
                'time' => time()
            ]);

            if ($type == 1) {
                $star = VideoModel::where('id', $rid)->value('star');
                VideoModel::update(['star' => $star + 1], ['id' => $rid]);
            } else if ($type == 2) {
                $star = VoiceModel::where('id', $rid)->value('star');
                VoiceModel::update(['star' => $star + 1], ['id' => $rid]);
            } else if ($type == 3) {
                $star = ArticleModel::where('id', $rid)->value('star');
                ArticleModel::update(['star' => $star + 1], ['id' => $rid]);
            }
            return show(200, '点赞成功');
        } else {
            StarModel::destroy($one['id']);

            if ($type == 1) {
                $star = VideoModel::where('id', $rid)->value('star');
                VideoModel::update(['star' => $star - 1], ['id' => $rid]);
            } else if ($type == 2) {
                $star = VoiceModel::where('id', $rid)->value('star');
                VoiceModel::update(['star' => $star - 1], ['id' => $rid]);
            } else if ($type == 3) {
                $star = ArticleModel::where('id', $rid)->value('star');
                ArticleModel::update(['star' => $star - 1], ['id' => $rid]);
            }
            return show(200, '取消点赞');
        }
    }
}
